﻿using System;
using System.IO;
using System.Text;

namespace Missbot.Common
{
    /// <summary>
    /// 文件日志记录器
    /// </summary>
    public static class FileLogger
    {
        /// <summary>
        /// 日志存放路径
        /// </summary>
        private const string LogPath = "./RuntimeLog/";

        /// <summary>
        /// 文件操作锁
        /// </summary>
        private static readonly object lockObj = new();

        /// <summary>
        /// 记录日志
        /// </summary>
        /// <param name="log">日志内容</param>
        public static void Log(string log)
        {
            lock (lockObj)
            {
                using var steam = CheckFile();
                var data = new UTF8Encoding().GetBytes($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}:{log}\n");
                steam.Write(data, 0, data.Length);

                //清空缓冲区、关闭流
                steam.Flush();
            }
        }

        /// <summary>
        /// 检查文件是否存在（如果不存在，则创建相应的文件夹及目录）
        /// </summary>
        /// <returns></returns>
        private static FileStream CheckFile()
        {
            var dir = new DirectoryInfo(LogPath);
            if (!dir.Exists)
            {
                dir.Create();
            }

            var fi = new FileInfo($"{LogPath}{DateTime.Now:yyyyMMdd}.log");
            return !fi.Exists ? fi.Create() : fi.Open(FileMode.Append, FileAccess.Write);
        }
    }
}